package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopier {
	  
	
	public static void copy(String fromFileName,String packageName, String toFileName)
      throws IOException {
		File fromFile = new File(fromFileName);
		

		if (!fromFile.exists())
			throw new IOException("FileCopy: " + "no such source file: "+ fromFileName);
		if (!fromFile.isFile())
			throw new IOException("FileCopy: " + "can't copy directory: "+ fromFileName);
		if (!fromFile.canRead())
			throw new IOException("FileCopy: " + "source file is unreadable: "+ fromFileName);
		File dir = new File(toFileName+"\\"+packageName);
		if (!dir.exists()){
			dir.mkdirs();
			
		}
		if (dir.isFile())
			throw new IOException("FileCopy: "+ "destination is not a directory: " + dir.getAbsolutePath());
		if (!dir.canWrite())
			throw new IOException("FileCopy: "+ "destination directory is unwriteable: " + dir.getAbsolutePath());
    
		File toFile = new File(dir.getAbsoluteFile()+"\\"+fromFile.getName());
		if(toFile.exists()){
			toFile.delete();
			toFile = new File(dir.getAbsoluteFile()+"\\"+fromFile.getName());
		}
		FileInputStream from = null;
		FileOutputStream to = null;
		try {
				from = new FileInputStream(fromFile);
				to = new FileOutputStream(toFile,false);
				byte[] buffer = new byte[4096];
				int bytesRead;

				while ((bytesRead = from.read(buffer)) != -1)
					to.write(buffer, 0, bytesRead); // write
		} catch(Throwable e){
			e.printStackTrace();
		}finally {
			if (from != null)
				try {
					from.close();
				} catch (IOException e) {}
			if (to != null)
				try {
					to.close();
				} catch (IOException e) {}
		}
  }
}
